/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.ipo.mm.web.actions;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.ipo.mm.ejb.entities.City;
import org.ipo.mm.ejb.entities.Institution;
import org.ipo.mm.ejb.entities.InstitutionFamily;
import org.ipo.mm.ejb.entities.InstitutionRegion;
import org.ipo.mm.ejb.entities.InstitutionType;
import org.ipo.mm.ejb.facade.city.CityFacadeLocal;
import org.ipo.mm.ejb.facade.family.InstitutionFamilyFacadeLocal;
import org.ipo.mm.ejb.facade.institution.InstitutionFacadeLocal;
import org.ipo.mm.ejb.facade.region.InstitutionRegionFacadeLocal;
import org.ipo.mm.ejb.facade.type.InstitutionTypeFacadeLocal;
import org.ipo.mm.web.formbeans.RepresentativeSearchBean;
import org.ipo.mm.web.util.BreadCrumbs;
import org.ipo.mm.web.util.ConstantManager;
import org.ipo.mm.web.util.pager.AbstractPager;
import org.ipo.mm.web.util.pager.RepresentativePager;

/**
 *
 * @author makcro
 */
public class RepresentativeSearchAction extends org.apache.struts.action.Action {

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        ActionForward actionForward = null;
        injectAdvSearchBaseData(request);
        AbstractPager pager = null;
        String pageNumber = request.getParameter("p");


        BreadCrumbs bc = (BreadCrumbs) request.getSession().getAttribute(ConstantManager.SESSION_BREADCRUMB_PARAM_NAME);
        String bcName = (pageNumber == null) ? ConstantManager.BC_REPR_LIST : ConstantManager.BC_REPR_LIST + "-" + pageNumber;
        bc.push(bcName, request);



        if (pageNumber == null) {

            RepresentativeSearchBean rsb = (RepresentativeSearchBean) form;

            String nameFilter = null;
            String nameOperator = null;

            String emailFilter = null;
            String emailOperator = null;

            String faxFilter = null;
            String faxOperator = null;

            String functionFilter = null;
            String functionOperator = null;

            String telephoneFilter = null;
            String telephoneOperator = null;

            String orderBy = null;

            String[] institutinFilter = null;
            String[] typeFilter = null;
            String[] regionFilter = null;
            String[] familyFilter = null;
            String[] cityFilter = null;
            //if user clicked some of speed search links

            //serch by institutions
            String iid = request.getParameter("iid");
            String orderByParam = request.getParameter("orderBy");

            if (iid != null) {

                institutinFilter = new String[]{iid};

                //user used advanced search form
            } else if (orderByParam != null) {
                orderBy = resolveOrderBy(orderByParam);
            } else {
                nameFilter = (rsb.getNameFilter() == null || "".equals(rsb.getNameFilter().trim()) ? null : rsb.getNameFilter().trim());
                nameOperator = rsb.getNameOperator();

                emailFilter = (rsb.getEmailFilter() == null || "".equals(rsb.getEmailFilter().trim()) ? null : rsb.getEmailFilter().trim());
                emailOperator = rsb.getEmailOperator();

                faxFilter = (rsb.getFaxFilter() == null || "".equals(rsb.getFaxFilter().trim()) ? null : rsb.getFaxFilter().trim());
                faxOperator = rsb.getFaxOperator();

                functionFilter = (rsb.getFunctionFilter() == null || "".equals(rsb.getFunctionFilter().trim()) ? null : rsb.getFunctionFilter().trim());
                functionOperator = rsb.getFunctionOperator();

                telephoneFilter = (rsb.getTelephoneFilter() == null || "".equals(rsb.getTelephoneFilter().trim()) ? null : rsb.getTelephoneFilter().trim());
                telephoneOperator = rsb.getTelephoneOperator();

                orderBy = resolveOrderBy(rsb.getOrderBy());


                typeFilter = rsb.getiTypeFilter();
                regionFilter = rsb.getiRegionFilter();
                familyFilter = rsb.getiFamilyFilter();
                cityFilter = rsb.getiCityFilter();
                institutinFilter = rsb.getInstitutionFilter();
            }



            pager = new RepresentativePager(
                    nameFilter,
                    nameOperator,
                    telephoneFilter,
                    telephoneOperator,
                    faxFilter,
                    faxOperator,
                    emailFilter,
                    emailOperator,
                    functionFilter,
                    functionOperator,
                    institutinFilter,
                    typeFilter,
                    regionFilter,
                    familyFilter,
                    cityFilter,
                    orderBy);

            request.getSession().setAttribute(ConstantManager.SESSION_REP_PAGER, pager);

        } else {

            pager = (AbstractPager) request.getSession().getAttribute(ConstantManager.SESSION_REP_PAGER);
            pager.setPageNumber(Integer.parseInt(pageNumber));

        }


        pager.doPaging(request);

        actionForward = mapping.findForward(ConstantManager.NAVIGATION_REPRESENTATIVE_LIST);

        return actionForward;
    }

    private void injectAdvSearchBaseData(HttpServletRequest request) {


        List<InstitutionRegion> regions = lookupInstitutionRegionFacade().findAll();
        List<InstitutionType> types = lookupInstitutionTypeFacade().findAll();
        List<InstitutionFamily> families = lookupInstitutionFamilyFacade().findAll();
        List<City> cities = lookupCityFacade().findAll();
        List<Institution> institutions = lookupInstitutionFacade().findAll();

        request.setAttribute("search_regions", regions);
        request.setAttribute("search_types", types);
        request.setAttribute("search_families", families);
        request.setAttribute("search_cities", cities);
        request.setAttribute("search_institutions", institutions);
    }

    private InstitutionTypeFacadeLocal lookupInstitutionTypeFacade() {
        try {
            Context c = new InitialContext();
            return (InstitutionTypeFacadeLocal) c.lookup("java:comp/env/InstitutionTypeFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private InstitutionRegionFacadeLocal lookupInstitutionRegionFacade() {
        try {
            Context c = new InitialContext();
            return (InstitutionRegionFacadeLocal) c.lookup("java:comp/env/InstitutionRegionFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private InstitutionFamilyFacadeLocal lookupInstitutionFamilyFacade() {
        try {
            Context c = new InitialContext();
            return (InstitutionFamilyFacadeLocal) c.lookup("java:comp/env/InstitutionFamilyFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private CityFacadeLocal lookupCityFacade() {
        try {
            Context c = new InitialContext();
            return (CityFacadeLocal) c.lookup("java:comp/env/CityFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private InstitutionFacadeLocal lookupInstitutionFacade() {
        try {
            Context c = new InitialContext();
            return (InstitutionFacadeLocal) c.lookup("java:comp/env/InstitutionFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private String resolveOrderBy(String code) {

        if ("1".equals(code)) {
            code = "lastName";
        } else if ("2".equals(code)) {
            code = "email";
        } else if ("3".equals(code)) {
            code = "telephone";
        } else if ("4".equals(code)) {
            code = "fax";
        } else if ("5".equals(code)) {
            code = "function";
        } else if ("6".equals(code)) {
            code = "institution.name";
        } else {
            code = "lastName";
        }

        return code;


    }
}
